package com.sekill.user.service;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.seckill.common.redis.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangguoming
 * 阿里云短信服务类
 */
@Service
public class AliyunSmsService {
	protected Logger logger = LoggerFactory.getLogger(AliyunSmsService.class);

	@Autowired
	private RedisService redisService;

	/** 阿里雲消息Key **/
	@Value("${aliyun.accessKeyId}")
    private String ACCESS_KEY_ID;
    /** 阿里雲消息Secret **/	
	@Value("${aliyun.accessKeySecret}")
    private String ACCESS_KEY_SECRET;


    /** 日短息发送次数 **/
    private static int maxSendNumOfDay = 10;
    /** 验证码长度：4位 **/
	private static int vcodeLength = 4;
    /** 验证码长度：4位 **/
    private String SMS_REDIS_Key = "sms:{}";


	//产品名称:云通信短信API产品,开发者无需替换
	static final String product = "Dysmsapi";
	//产品域名,开发者无需替换
	static final String domain = "dysmsapi.aliyuncs.com";

    /**
     * SmsRedisKey
     * @param phoneNum
     * @return
     */
    private String getSmsRedisKey(String phoneNum) {
        return "sms:"+phoneNum;
	}

    /**
     * 发送短信验证码
     * 每日最多获取3条验证码
     * @param phoneNum
     * @return
     */
    public boolean sendVerifyCode(String phoneNum) {
    	String signName = "社区小纸条";
    	String tempCode = "SMS_75770182";
		Map<String, Object> params = new HashMap<>();
    	String verifyCode = getVerifyCode();
    	logger.info("getVerifyCode {} for {}",verifyCode,phoneNum);
		params.put("vcode", verifyCode);
		if(sendSms(phoneNum, tempCode, params, signName)) {
//			redisService.set(getSmsRedisKey(phoneNum), verifyCode, 60*10L);
			redisService.setCacheObject(getSmsRedisKey(phoneNum),verifyCode,60*10L, TimeUnit.SECONDS);
			return true;
		}
		return false;
	}
    /**
     * 验证verifyCode
     * @param phoneNum
     * @param verifyCode
     * @return
     */
    public Boolean checkVerifyCode(String phoneNum,String verifyCode) {
    	String redisKey = getSmsRedisKey(phoneNum);
    	Object code = redisService.getCacheObject(redisKey);
    	if(code==null) {
    		return false;
    	}
    	if(code.toString().equals(verifyCode)) {
    		redisService.deleteObject(redisKey);
    		return true;
    	}
		return false;
	}
    /**
     * 获取短信验证码
     * 默认6位数字
     * @return
     */
    public String getVerifyCode() {
    	return getVerifyCode(vcodeLength);
    }
    /**
     * 获取短信验证码
     * @param length 最短4位
     * @return
     */
    public String getVerifyCode(int length) {
    	if(length<vcodeLength){
    		length = vcodeLength;
    	}
    	String code = "";
    	Random random = new Random();
    	while(true){
    		int x = random.nextInt(10);
    		if(x!=4){
    			code+=x;
    		}
    		if(code.length()==length){
    			break;
    		}
    	}
		return code;
	}
    /**
     * 发送短信消息
     * @param phoneNum
     * @param templateCode
     * @param params
     * @param signName
     * @return
     */
    public boolean sendSms(String phoneNum, String templateCode, Map<String,Object> params, String signName) {
		com.aliyun.dysmsapi20170525.Client client = null;
		try {
			client = this.createClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
			SendSmsRequest sendSmsRequest = new SendSmsRequest()
					.setPhoneNumbers(phoneNum)
					.setSignName(signName)
					.setTemplateCode(templateCode)
					.setTemplateParam(JSON.toJSONString(params));
			// 复制代码运行请自行打印 API 的返回值
			SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
    }

	/**
	 * 使用AK&SK初始化账号Client
	 * @param accessKeyId
	 * @param accessKeySecret
	 * @return Client
	 * @throws Exception
	 */
	public com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
		Config config = new Config()
				// 您的AccessKey ID
				.setAccessKeyId(accessKeyId)
				// 您的AccessKey Secret
				.setAccessKeySecret(accessKeySecret);
		// 访问的域名
		config.endpoint = "dysmsapi.aliyuncs.com";
		return new com.aliyun.dysmsapi20170525.Client(config);
	}


}
